package com.feng.service.impl;


import com.feng.Exception.SystemException;
import com.feng.component.MsmComponent;
import com.feng.domain.ResponseResult;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.service.MsmService;
import com.feng.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {
    @Autowired
    private MsmComponent smsComponent;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Transactional
    @Override
    public ResponseResult sendMsm(String phone) {
        if(!StringUtils.hasText(phone)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_NOT_NULL);
        }
        //2.如果redis获取不到进行阿里云的发送
        //生成随机值，传递给阿里云进行发送
       String code = RandomUtil.getFourBitRandom();
        try {
            //阿里云发送验证码
            smsComponent.sendSmsCode(code,phone);
            //发送成功后将验证码放到redis中，设置有效时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();

        }
        //调用service发送短信的方法
      return  ResponseResult.okResult();
    }
}
